package com.ambulance.project.biz.util.xml;


/***
 *  @description
 *  @author z
 *  @date: 2020/9/24
 *  @version: v1.0
 */

import com.ambulance.project.biz.entity.Dispatch;
import com.ambulance.project.biz.service.DispatchService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;

@Component
public class FileMonitor implements CommandLineRunner
{

	@Value("${mairy.ftpPath}")
	private String xmlSourcePath;

	@Value(("${mairy.xmlPath}"))
	private String xmlDescPath;

	@Autowired
	private DispatchService dispatchService;


	/**
	 * 获取当前调度
	 */
	public String getDispatch()
	{

		Integer dispatchID = 10;
		try
		{
			QueryWrapper<Dispatch> wrapper = new QueryWrapper<>();
			wrapper.gt("status", 3).lt("status", 8).orderByDesc("dispatchID").last("limit 1");
			Dispatch one = dispatchService.getOne(wrapper);
			dispatchID = one.getDispatchID();
		} catch (Exception e)
		{
			e.printStackTrace();

		}
		return "" + dispatchID;
	}

	/**
	 * 文件拷贝
	 *
	 * @param sourcePath
	 * @param descPath
	 */
	public void copyFile(String sourcePath, String descPath)
	{
		Path source = Paths.get(sourcePath);
		Path desc = Paths.get(descPath);
		try
		{
			Files.copy(source, desc);
			File file = new File(sourcePath);
			if (file.exists() && file.isFile())
			{
				file.delete();
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 文件监控
	 * 监听文件路径，获取xml文件，复制到目标路径下并放到对应的调度目录下
	 *
	 * @throws Exception
	 */
	public void fileCheck() throws Exception
	{
		WatchService watchService = FileSystems.getDefault().newWatchService();
		Paths.get(xmlSourcePath).register(watchService,
				StandardWatchEventKinds.ENTRY_CREATE);
		while (true)
		{
			WatchKey key = watchService.take();
			for (WatchEvent<?> event : key.pollEvents())
			{
				String context = event.context().toString();
				String fileName = xmlSourcePath + context;
				System.out.println("获取原始文件路径" + fileName);
				String dispatch = getDispatch();
				// 拷贝到指定目录
				copyFile(fileName, xmlDescPath + dispatch + File.pathSeparator + context);
			}
			if (!key.reset())
			{
				break;
			}
		}
	}

	@Override
	public void run(String... args) throws Exception
	{
		System.out.println("开始文件监听 start");
		fileCheck();
		System.out.println("开始文件监听 成功");
	}
}
